package org.janusproject.demos.acl.request.role;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.janusproject.acl.protocol.ProtocolResult;
import org.janusproject.acl.protocol.request.FipaRequestProtocol;
import org.janusproject.kernel.crio.core.Role;
import org.janusproject.kernel.status.Status;
import org.janusproject.kernel.status.StatusFactory;

public class Answerer extends Role {

	private State state;
	private FipaRequestProtocol requestProtocol;
	private ProtocolResult request;
	
	@Override
	public Status live() {
		state = HandleRequest();
		return StatusFactory.ok(this);
	}
	
	public Status activate(Object... parameters) {
		
		for (Object parameter : parameters) {
			if (parameter instanceof FipaRequestProtocol) {
				requestProtocol = (FipaRequestProtocol) parameter;
				state = State.WAITING_REQUEST;
				return StatusFactory.ok(this);
			}
		}
		
		return StatusFactory.cancel(this);
	}
	
	private State HandleRequest() {
		
		if( requestProtocol.hasFailed() ){
			leaveMe();
		}
		
		switch (this.state) 
		{
			case WAITING_REQUEST: 
			{
				request = requestProtocol.getRequest();
				
				if( request != null ){
					log("request received");
					return State.SENDING_ANSWER;
					
					//requestProtocol.notUnderstood("?");
					//return State.DONE;
				}
				
				return State.WAITING_REQUEST;
			}
			case SENDING_ANSWER:
			{
				if( request.getContent().toString().equalsIgnoreCase("friend") ){
					requestProtocol.agree("yeah!");
					log("agreement sent");
					return State.SENDING_RESULT;
				}
				else{
					requestProtocol.refuse("wtf?!");
					log("refusal sent");
					return State.DONE;
				}
			}
			case SENDING_RESULT:
			{
				requestProtocol.informDone("Let's meet tonight!");
				log("result sent");
				return State.DONE;
			}
			case DONE:
			{
				log("done");
				request = null;
				leaveMe();
			}
		default:
			return this.state;
		}
	}
	
	private void log(String str){
		Logger.getAnonymousLogger().log(Level.INFO, "[" + getPlayer() + "] : " + str);
	}
	
	public enum State{
		WAITING_REQUEST,
		SENDING_ANSWER,
		SENDING_RESULT,
		DONE;
	}
}
